package common;


import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by chen_ on 2017/5/5.
 */
public class Util {
    static OkHttpClient client = new OkHttpClient();

    public static String req(String url) throws IOException {
        Request request = new Request.Builder().url(url).header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36").build();
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public static void download(String url, String filename) {
        try {
            Request request = new Request.Builder().url(url).build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
//                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        throw new IOException("Failed to download file: " + response);

                    }
                    //文件父目录不存在会自动创建
                    File file = new File(filename);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(response.body().bytes());
                    fos.close();
                }
            });
        } catch (Exception e) {
//           e.printStackTrace();
        }
    }
}
